package com.csit.dao.impl;

import java.util.Date;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.csit.bean.Pager;
import com.csit.dao.WastageDao;
import com.csit.entity.Wastage;

/**
 * 
 * @Description:损耗dao的实现类
 * @Copyright: 福州骏华信息有限公司 (c)2012
 * @Created Date : 2012-12-8
 * @author longweier
 * @vesion 1.0
 */
@Repository
public class WastageDaoImpl extends BaseDaoImpl<Wastage, Integer> implements WastageDao {

	@SuppressWarnings("unchecked")
	public Map<String, Double> queryTotal(Wastage wastage, Date beginDate,Date endDate) {
		StringBuilder hql = new StringBuilder(
				"select sum(isnull(a.quantity,0)) as totalQty,sum(isnull(a.amount,0)) as totalAmount from Wastage a where 1=1");
		if (wastage.getShop() != null) {
			hql.append(" and a.shop=:shop");
		}
		if (wastage.getProduct() != null) {
			hql.append(" and a.product=:product");
		}
		if (beginDate != null) {
			hql.append(" and a.createDate>=:beginDate");
		}
		if (endDate != null) {
			hql.append(" and a.createDate<=:endDate");
		}
		Query query = getSession().createQuery(hql.toString());

		if (wastage.getShop() != null) {
			query.setEntity("shop", wastage.getShop());
		}
		if (wastage.getProduct() != null) {
			query.setEntity("product", wastage.getProduct());
		}
		if (beginDate != null) {
			query.setDate("beginDate", beginDate);
		}
		if (endDate != null) {
			query.setDate("endDate", endDate);
		}
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

		return (Map<String, Double>) query.uniqueResult();
	}

	public Pager queryWastageList(Pager pager, Wastage wastage, Date beginDate,Date endDate) {
		Criteria criteria = getSession().createCriteria(Wastage.class);
		if(wastage.getShop()!=null){
			criteria.add(Restrictions.eq("shop", wastage.getShop()));
		}
		if(wastage.getProduct()!=null){
			criteria.add(Restrictions.eq("product", wastage.getProduct()));
		}
		if(beginDate!=null){
			criteria.add(Restrictions.ge("createDate", beginDate));
		}
		if(endDate!=null){
			criteria.add(Restrictions.le("createDate", endDate));
		}
		Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

		criteria.setProjection(null);
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		criteria.setFirstResult(pager.getBeginCount());
		criteria.setMaxResults(pager.getPageSize());
		criteria.addOrder(Order.desc("createDate"));
		pager.setTotalCount(totalCount);
		pager.setList(criteria.list());
		return pager;
	}

}
